/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/island-perimeter
   @Language: C++
   @Datetime: 19-05-14 09:53
   */

class Solution {
public:
	/**
	 * @param grid: a 2D array
	 * @return: the perimeter of the island
	 */
	int islandPerimeter(vector<vector<int> > &grid) {
		// Write your code here
		int perimeter=0, n=grid.size(), m=grid[0].size();
		for(int i=0; i<n; ++i){
			for(int j=0; j<m; ++j){
				if(grid[i][j]==0) continue;
				if(i==0 || (i-1>=0 && grid[i-1][j]==0)) ++perimeter;
				if(i+1==n ||(i+1<n && grid[i+1][j]==0)) ++perimeter;
				if(j==0 || (j-1>=0 && grid[i][j-1]==0)) ++perimeter;
				if(j+1==m ||(j+1<m && grid[i][j+1]==0)) ++perimeter;
			}
		}
		return perimeter;
	}
};
